'use strict'

let http = require('http')
let uuidV1 = require('uuid/v1');
let uuidV4 = require('uuid/v4');
let Redis = require ('ioredis');
let Command = require('ioredis').Command;
let utils = require('ioredis/lib/utils')
let redis_config = require('./config/redis.json')
let bodyParser = require ('body-parser');
let request = require('request')
let express = require('express')
let app = express();
app.server = http.createServer(app);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//支持跨域
app.use(( req, res ,next) => {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

app.post('/seckill-login',function(req,res,next){
    let result = {}
    // let userId=getrandom();
    let userId=req.body.username;
    console.log(req.body)
    let token=uuidV1();
    let redis = new Redis(redis_config);
    result["userId"]=userId;
    result["token"] = token;
//    console.log("userId:" + userId);
    redis.set(userId,token , (err, result) => {
        if (err) {
            console.log("token缓存失败：" + err);
        } else {
            console.log("token缓存成功.");
        }
    });
    res.json(result)
})

app.get("/seckill-login/products",function(req,res,next){
    let redis = new Redis(redis_config);
    var get = new Command('lrange', ['releaseList', 0, 0], 'utf8', function (err, input) {
        let productId = utils.convertBufferToString(input, 'utf8');
        console.log('productId: ' + productId[0])        
        let result = {
            payload:[
                {id: productId[0]}
            ]
        }
        res.status(200).json(result);
    });
     redis.sendCommand(get);
})

app.post("/seckill-login/publication/:id", function(req, res, next){
    let data = req.body;
    let productId = req.params.id;
    let options = {
        uri:`http://47.94.129.86:3004/seckill/manager/api/v1/seckillInfo/${productId}`,
        method:"post",
        json: data
    }
    request(options, (error, response, body) => {
        const result = {
            response: response,
            body: body,
            error: error
        }
        if (!error && (response.statusCode == 200)) {
             let redis = new Redis(redis_config);
             redis.lpush('releaseList', productId)
             console.log('success: ' + productId)
             res.json({isSuccess: 'success'})
        } else {
             res.status(500).json({isSuccess: 'fail', message: response.body.message})
        }
    })
})

app.server.listen(process.env.PORT || 4000);

function getrandom() {
     var res = "";
     for(var i = 0; i < 5 ; i ++) {
         var id = Math.ceil(Math.random()*9);
         res += id;
     }
     //console.log('res:'+res);
     return "00"+res;
}
//console.log('test: ' + getrandom());

//创建服务器
// let server = http.createServer(function (req, res) {
//     if (req.url === '/seckill-login' && req.method.toLowerCase() === 'post') {
//         let alldata = ''
//         req.on('data', function (chunk) {
//             alldata += chunk
//         })
//         req.on('end', function () {
//             console.log(alldata)
//             let result = {}
//             let userId=uuidV4();
//             let token=uuidV1();
//             let redis = new Redis(redis_config);
//             result["userId"]=userId;
//             result["token"] = token;
//             redis.set(token, token, (err, result) => {
//                 if (err) {
//                     console.log("token缓存失败：" + err);
//                 } else {
//                     console.log("token缓存成功.");
//                 }
//             });
//             res.end(JSON.stringify(result))
//         })
//     }
// })

// //设置监听端口
// server.listen(4000, function () {
//     console.log("server is started listen port 4000")
// })